<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="basicForm"
        formItemWidth="130px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showSelectCol
        showActionCol
        :showPagination="isShowPagination"
        :tableHeight="480"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :selectionChange="handleSelectionChange"
        :checkSelectable="checkSelectable"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <!-- 按钮操作栏 -->
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <!-- 库存数量查看弹框 -->
    <StockNumDialog
      ref="stockNum"
      :visible.sync="stockNum.visible"
      :stockKey="stockNum.stockKey"
    />
    <!-- 选择替代商品弹框 -->
    <SelectReplaceProductDialog
      :visible.sync="selectReplaceProduct.visible"
      :product-kind="selectReplaceProduct.productKind"
      @getResults="getSelectedReplaceProduct"
    />
    <!-- 高级关联 - 停用弹框 -->
    <ReplaceProductSeniorDialog
      ref="replaceSenior"
      :visible.sync="seniorLinkedStop.visible"
      @seniorSearchResult="getTableDataBySeniorStop"
    />
    <!-- 高级关联 - 启用弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinkedEnable.visible"
      :columns="seniorLinkedEnable.columns"
      :dataSource="seniorLinkedEnable.dataSource"
      @seniorSearchResult="getTableDataBySeniorEnable"
    />
    <!-- 提交原因- 启用弹框 -->
    <input-reason-dialog
      ref="reasonRef"
      labelWidth="120px"
      :visible.sync="batchEnable.visible"
      :submitLoading="batchEnable.loading"
      :handleSubmit="batchSubmitEnableSkuInfo"
    >
      <el-form-item slot="form-header" label="是否跟随上架" required>
        <el-select v-model="batchEnable.isFollowShelf" clearable>
          <el-option
            v-for="item in batchEnable.isFollowShelfOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
    </input-reason-dialog>
    <!-- 提交原因- 停用弹框 -->
    <StopOrDownSubmittedDialog
      isStopSku
      :submitLoading="batchStop.loading"
      :visible.sync="batchStop.visible"
      :specialSubmit="batchSubmitStopSkuInfo"
      :hasSales="hasSales"
    />
    <!-- 历史记录查询弹框 -->
    <ShowListDialog
      :visible.sync="showList.visible"
      :dialogTitle="showList.title"
      :tableLoading="showList.loading"
      :tableColumns="showList.columns"
      :tableData="showList.list"
    />
    <!-- 客户平台 -->
    <ShowListDialog
      :visible.sync="platform.visible"
      :dialogTitle="platform.title"
      :tableColumns="platform.columns"
      :search-list="getPlatformDetail"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import ShowListDialog from '@/components/ShowListDialog';
import InputReasonDialog from '@/components/InputReasonDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import StockNumDialog from '@/pages/commodity/components/StockNumDialog';
import SelectReplaceProductDialog from '@/pages/commodity/components/SelectReplaceProductDialog';
import ReplaceProductSeniorDialog from '@/pages/commodity/components/ReplaceProductSeniorDialog';
import StopOrDownSubmittedDialog from '@/pages/commodity/components/StopOrDownSubmittedDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { getInitFormData } from '@/utils/getUtils';
import {setAuthBtnId, removeSessionByRoute, createExcelByExport} from '@/utils/bizUtils';
import { FORM_ITEMS, getTableColumns } from './constants/toHandle';
import { HISTORY_LIST_COLUMNS, PLATFORM_TABLE_COLUMNS } from './constants';
import { WHETHER_OPTIONS, WhetherEnum } from '@/constants/basics';
import {
  getHandlingListService,
  searchSeniorLinkedStopService,
  searchSeniorLinkedEnableService,
  submitStopInfoService,
  submitEnableInfoService,
  getHistoryRecordsService,
  exportExcelService,
  getPlatformDetailService
} from '@/api/commodity/commodityManage/stopOrEnableManage';
import { manageAreaSearchService } from '@/api/public';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    StockNumDialog,
    ShowListDialog,
    InputReasonDialog,
    SeniorLinkedDialog,
    SelectReplaceProductDialog,
    ReplaceProductSeniorDialog,
    StopOrDownSubmittedDialog,
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      // 表格信息
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      pageSizes: [10, 100, 1000],
      // 库存数量弹框
      stockNum: {
        visible: false,
        stockKey: ''
      },
      // 选择替代商品弹框
      selectReplaceProduct: {
        visible: false,
        productKind: '',
        selectIndex: -1
      },
      // 高级关联 - 停用
      seniorLinkedStop: {
        visible: false,
        relParamList: [], // 查询结果
      },
      // 高级关联 - 启用
      seniorLinkedEnable: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }]
      },
      // 批量启用
      batchEnable: {
        visible: false,
        loading: false,
        isFollowShelf: '',
        isFollowShelfOptions: WHETHER_OPTIONS
      },
      // 批量停用
      batchStop: {
        visible: false,
        loading: false
      },
      // 模板导出
      export: {
        loading: false
      },
      showList: {
        visible: false,
        title: '历史停启用记录',
        loading: false,
        columns: HISTORY_LIST_COLUMNS,
        list: []
      },
      isShowPagination: true, // 是否展示分页，默认展示
      extraParams: {},
      platform: {
        visible: false,
        title: '客户平台明细',
        columns: PLATFORM_TABLE_COLUMNS,
        skuNo: ''
      },
    }
  },
  mounted () {
    this.setAreaOptions()
    this.tableInfo.columns = getTableColumns({
      handleViewStockInfo: this.handleViewStockInfo,
      handleSelectReplaceProduct: this.handleSelectReplaceProduct,
      handleViewPlatformDetail: this.handleViewPlatformDetail
    });
    this.runWaitItems();
  },
  beforeRouteLeave (to, from, next) {
    removeSessionByRoute({
      toName: to.name,
      notRemoveNames: 'stopOrEnableManageToHandle',
      cacheKey: this.$route?.query?.cacheKey
    })
    next();
  },
  computed: {
    // 没有表格勾选
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    },
    // 展示批量停用按钮栏
    isShowStopBtnsBar () {
      const isEmptyTable = this.tableInfo.list.length === 0;
      if (isEmptyTable) return true;
      const isShowEnableSku = this.tableInfo.list[0].enableStatus === '1';
      return isShowEnableSku; // 当前展示启用时，展示停用按钮，反之展示启用按钮
    },
    hasSales () {
      return this.tableInfo.selection.some(item => item.sales > 0);
    }
  },
  methods: {
    runWaitItems () {
      const { skuNo, cacheKey, spuNo } = this.$route.query;
      let isGetTableData = false;
      // 淘汰商品停用
      if (skuNo) {
        this.extraParams.skuNo = skuNo;
        this.formData.skuNo = skuNo;
        isGetTableData = true;
      }
      // 淘汰商品批量停用
      if (cacheKey) {
        this.extraParams.skuNos = JSON.parse(sessionStorage.getItem(cacheKey)) ?? [];
        isGetTableData = true;
      }
      // 销售区域库存信息详情查看
      if (spuNo) {
        this.extraParams.spuNo = spuNo;
        this.formData.spuNo = spuNo;
        isGetTableData = true;
      }
      if (isGetTableData) {
        this.getTableData();
      }
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const menuId = sessionStorage.getItem('menuId')
      const buttonId = sessionStorage.getItem('buttonId')
      // 批量启用按钮栏
      const enableBtnsBar = [
        {
          label: '批量启用',
          method: this.handleBatchEnable,
          disabled: this.hasNoSelection,
          icon: 'el-icon-open'
        },
        {
          label: '高级关联-启用',
          method: this.handleSeniorLinkByEnable,
          icon: 'el-icon-open'
        }
      ];
      // 批量停用按钮栏
      const stopBtnsBar = [
        {
          label: '批量停用',
          method: this.handleBatchStop,
          disabled: this.hasNoSelection,
          icon: 'el-icon-turn-off'
        },
        {
          label: '高级关联-停用',
          method: this.handleSeniorLinkByStop,
          icon: 'el-icon-turn-off'
        },
        {
          label: '替代商品模板导出',
          method: this.handleExportTemplate,
          loading: this.export.loading,
          disabled: this.tableInfo.list.length === 0
        },
        {
          label: '替代商品导入',
          action: `sysback/finish/sku/enable/list/importExcel?menuId=${menuId}&buttonId=${buttonId}&productKind=${this.formData.productKind}`,
          methods: {
            handleUploadSuccess: (res) => {
              this.isShowPagination = false;
              this.tableInfo.list = res.retData;
            },
            handleBeforeUpload: () => {
              this.tableInfo.loading = true;
              setAuthBtnId('查询');
            }
          },
          isImport: true,
          loadingFn: state => { this.tableInfo.loading = state }
        }
      ];
      const btnsBar = this.isShowStopBtnsBar ? stopBtnsBar : enableBtnsBar;
      // 按钮通用属性填充
      const finalBars = btnsBar.map(item => ({
        ...item, type: 'primary', size: 'mini', hasAuth: true
      }));
      return getBtnsBar(h, finalBars, this.showBtn, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '查看历史记录', method: this.handleViewHistoryRecord }];
      return getTableAction({ h, row, actionList })
    },
    // 根据审核状态禁用表格勾选 - 审核中不可勾选
    checkSelectable ({ row }) {
      return row.auditState !== 'AUDITING';
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 批量启用
    handleBatchEnable () {
      this.batchEnable.visible = true;
    },
    // 批量停用
    handleBatchStop () {
      this.batchStop.visible = true;
    },
    // 高级关联-启用
    handleSeniorLinkByEnable () {
      this.seniorLinkedEnable.visible = true;
    },
    // 高级关联-停用
    handleSeniorLinkByStop () {
      this.seniorLinkedStop.visible = true;
    },
    // 模板导出
    async handleExportTemplate () {
      const loadingFn = state => { this.export.loading = state };
      const res = await exportExcelService(this.tableInfo.list, loadingFn);
      createExcelByExport({ res, excelTitle: `SKU停启用信息` });
    },
    // 查看库存信息
    handleViewStockInfo ({ row, key }) {
      this.stockNum.visible = true;
      this.stockNum.stockKey = key;
      this.$nextTick(() => {
        this.$refs.stockNum.getSearchParams({ skuNo: row.skuNo });
      });
    },
    // 选择替代商品
    handleSelectReplaceProduct ({ index }) {
      this.selectReplaceProduct.visible = true;
      this.selectReplaceProduct.productKind = this.formData.productKind
      this.selectReplaceProduct.selectIndex = index;
    },
    // 查看历史记录
    handleViewHistoryRecord (row) {
      this.showList.visible = true;
      this.getTableDataByHistoryRecord(row.skuNo);
    },
    // 获取选择的替代商品信息
    getSelectedReplaceProduct (data) {
      const index = this.selectReplaceProduct.selectIndex;
      if (index === -1) return false;
      const isSelectSelf = data.skuNo === this.tableInfo.list[index].skuNo;
      if (isSelectSelf) return this.$message.warning('替代商品不能选择自己');
      this.$refs.skusTable.$refs.plTable.clearSelection(); // 选择替代商品，就清空之前的表格勾选，重新进行勾选
      this.tableInfo.list[index].replaceSkuNo = data.skuNo;
      this.tableInfo.list[index].replaceProductName = data.productName;
    },
    // 获取表格信息 - 表单查询
    async getTableData () {
      this.isShowPagination = true;
      setAuthBtnId('查询');
      const data = { ...this.formData, ...this.paginationParams, ...this.extraParams };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await getHandlingListService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData.results;
        this.setTotalNum(retData.totalNum);
      }
    },
    // 高级关联 - 停用 - 查询结果
    async getTableDataBySeniorStop (relParamList) {
      this.isShowPagination = false;
      setAuthBtnId('高级关联');
      const data = { relParamList, productKind: this.formData.productKind };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await searchSeniorLinkedStopService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData;
      }
    },
    // 高级关联 - 启用 - 查询结果
    async getTableDataBySeniorEnable (skuNos) {
      this.isShowPagination = false;
      setAuthBtnId('高级关联');
      const data = { skuNos, productKind: this.formData.productKind };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await searchSeniorLinkedEnableService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData;
      }
    },
    // 批量启用 - 提交启用商品信息
    async batchSubmitEnableSkuInfo (commitReason) {
      setAuthBtnId('批量启用');
      const data = {
        skuNos: this.tableInfo.selection.map(item => item.skuNo),
        commitReason,
        isFollowShelf: this.batchEnable.isFollowShelf,
        productKind: this.formData.productKind,
      };
      const loadingFn = state => { this.batchEnable.loading = state };
      const retStatus = await submitEnableInfoService(data, loadingFn);
      if (retStatus) {
        this.$message.success('批量启用成功');
        this.resetAllState();
        this.batchEnable.visible = false;
      }
    },
    // 停用校验
    validateStopSku (reasonData, callback) {
      const hasCannotStop = this.tableInfo.selection.some(item => item.platformEnableStop == WhetherEnum.No && item.platformDetail > 0) // 客户平台不允许停用且客户平台明细不为0
      const noNeedCheckTypes = ['1', '4'] // 1 - 厂家停产; 4 - 夕阳产品
      if (noNeedCheckTypes.includes(reasonData?.commitReasonType)) return
      if (hasCannotStop) return this.$message.warning('客户平台已上架此商品，如需停用请先联系我司渠道运营人员')
      return this.$confirm('客户平台已上架此商品，是否确定发起停用？', '提示', {
        type: 'warning',
      }).then(() => {
        callback(reasonData)
      }).catch(() => {})
    },
    // 批量停用 - 提交停用商品信息
    batchSubmitStopSkuInfo (reasonData, callback) {
      const submitRequest = async reasonData => {
        setAuthBtnId('批量停用');
        const disableParamList = this.tableInfo.selection.map(item => ({
          skuNo: item.skuNo, replaceSkuNo: item.replaceSkuNo
        }));
        const data = {
          disableParamList,
          ...reasonData,
          productKind: this.formData.productKind,
        };
        const loadingFn = state => { this.batchStop.loading = state };
        const retStatus = await submitStopInfoService(data, loadingFn);
        if (retStatus) {
          this.$message.success('批量停用成功');
          this.resetAllState();
          callback()
        }
      }
      const cannotSubmit = this.validateStopSku(reasonData, submitRequest)
      if (cannotSubmit) return
      submitRequest(reasonData)
    },
    // 获取历史记录列表
    async getTableDataByHistoryRecord (skuNo) {
      const data = { skuNo };
      const loadingFn = state => { this.showList.loading = state };
      const retData = await getHistoryRecordsService(data, loadingFn);
      if (retData) {
        this.showList.list = retData;
      }
    },
    // 重置所有状态
    resetAllState () {
      this.tableInfo.list = []; // 表格清空
      // this.$refs.basicForm.handleResetForm(); // 清空表单
      this.formData = getInitFormData(FORM_ITEMS); // 清空表单
      this.$refs.replaceSenior.resetAllData(); // 高级关联 - 停用弹框数据清空
      this.seniorLinkedEnable.dataSource = []; // 高级关联 - 启用弹框数据清空
    },
    // 查看客户平台明细
    handleViewPlatformDetail ({ row }) {
      this.platform.skuNo = row.skuNo
      this.platform.visible = true
    },
    // 获取客户平台明细
    async getPlatformDetail (paginationParams, loadingFn) {
      const data = { skuNo: this.platform.skuNo }
      const res = await getPlatformDetailService(data, loadingFn)
      return res
    },
    // 区域下拉集合
    async setAreaOptions () {
      const res = await manageAreaSearchService()
      const index = this.formItems.findIndex(item => item.prop == 'manageAreaId')
      if (index > -1) this.formItems[index].options = res?.retData ?? []
    },
  }
}
</script>
